import TableList from '@/components/TableList';
import {deviceList, deviceCreate, deviceUpdate, deviceDelete, deviceStartup, deviceShutdown} from '@/pages/device/service';
import {PageContainer} from '@ant-design/pro-components';
import '@umijs/max';
import {message, Modal,Badge, Drawer} from "antd";
import FormModal from "@/components/FormModal";
import {useRef, useState} from "react";
import TOButton from "@/components/TableList/TOButton";
import TableOperations from "@/components/TableList/TableOperations";
import DeviceForm from "@/pages/device/components/DeviceForm";
import { render } from '@testing-library/react';
import CommandFormMgr from './components/CommandForm';

const DeviceMgr = () => {
  const [formModalVisible, setFormModalVisible] = useState(false);
  const [selectRecord, setSelectRecord] = useState(null);
  const [commandModalOpen, setCommandModalOpen] = useState(false)
  const tableRef = useRef();
  const formRef = useRef();
  const {confirm} = Modal;


  const columns = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 50,
    },
    {
      title: '设备名',
      dataIndex: 'name',
      width: 100,
    },
    {
      title: '设备号',
      dataIndex: 'deviceId',
      width: 100,
    },
    {
      title: '通讯号',
      dataIndex: 'commId',
      width: 100,
    },
    {
      title: '车牌号',
      dataIndex: 'plateNumber',
      width: 100,
    },
    {
      title: '线路',
      dataIndex: 'routeName',
      width: 100,
    },
    {
      title: '服务器',
      dataIndex: 'serverName',
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'connectStateName',
      width: 80,
      render: (_, record) => {
        return record.connectState == 0 ? <Badge status="error" text={record.connectStateName} />
          : record.connectState == 1 ? <Badge status="processing" text={record.connectStateName} />
          : <Badge status="success" text={record.connectStateName} />
        }
    },
    {
      title: '连接时间',
      dataIndex: 'connectTime',
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      width: 100,
      search: false,
      render: (_, record) => {
        const operations = [];
        if(record.connectState == 0){
          operations.push(<TOButton
                    key='connect'
                    type='primary'
                    text='启动'
                    onClick={() => {
                      confirm({
                        title: '启动设备',
                        content: `是否启动 “${record.name}” 设备？`,
                        async onOk() {
                          await deviceStartup({id: record.id});
                          message.success('启动成功')
                          tableRef.current.reload();
                        }
                      });
                    }}
                  />)
        }else{
          operations.push(<TOButton
          key='disconnect'
          type='primary'
          text='关闭'
          onClick={() => {
            confirm({
              title: '关闭设备',
              content: `是否关闭 “${record.name}” 设备？`,
              async onOk() {
                await deviceShutdown({id: record.id});
                message.success('关闭成功')
                tableRef.current.reload();
              }
            });
          }}
        />)
        }

        operations.push(<TOButton
          key='config'
          type='primary'
          text='配置'
          onClick={() => {
            setSelectRecord(record)
            setCommandModalOpen(true)
          }}
        />)
        operations.push(<TOButton
          key='config'
          type='primary'
          text='日志'
          onClick={() => {
            setSelectRecord(record)
            setCommandModalOpen(true)
          }}
        />)
        operations.push(<TOButton
          key='edit'
          type='primary'
          text='修改'
          onClick={() => {
            setSelectRecord(record)
            setFormModalVisible(true)
          }}
        />)

        operations.push(<TOButton
          key='del'
          type='danger'
          text='删除'
          onClick={() => {
            confirm({
              title: '删除设备',
              content: `是否删除“${record.code}”设备？`,
              async onOk() {
                await deviceDelete({id: record.id});
                message.success('删除成功')
                tableRef.current.reload();
              }
            });
          }}
        />)
        return <TableOperations operations={operations} /> ;
      }
    }
  ];

  const addCallback = () => {
    if (selectRecord) setSelectRecord(null)
    setFormModalVisible(true)
  };

  return (
    <PageContainer>
      <TableList
        tableRef={tableRef}
        columns={columns}
        keyName="id"
        labelWidth={95}
        tableRequest={deviceList}
        addCallback={addCallback}
        toolBarLeftArea="设备列表"
      />
      <FormModal
        title={`${selectRecord ? '修改' : '新增'}设备`}
        formRef={formRef}
        initFormValue={selectRecord || {isCheck: true, state: true}}
        visible={formModalVisible}
        onVisibleChange={visible => {
          setFormModalVisible(visible)
          if (!visible && selectRecord) {
            setSelectRecord(null)
          }
        }}
        labelCol={5}
        onConfirm={
          async (values) => {
            let request = selectRecord ? deviceUpdate : deviceCreate
            if (selectRecord) values.id = selectRecord.id
            values.state = values.state ? 1 : 0
            try {
              await request(values)
              message.success('提交成功')
              tableRef.current.reload()
              return true
            } catch (e) {
              return false
            }
          }
        }
      >
        <DeviceForm
          formRef={formRef}
          record={selectRecord}
        />
      </FormModal>

      <Drawer 
        destroyOnClose={true}
        title="配置" 
        width={1024} 
        closable={{ 'aria-label': 'Close Button' }} 
        open={commandModalOpen} 
        onClose={() => {setCommandModalOpen(false)}} >

        <CommandFormMgr 
        record={selectRecord} 
        closeDrawer={() => {setCommandModalOpen(false)}}/>

      </Drawer>
    </PageContainer>
  );
};
export default DeviceMgr;
